import requests
import json
import pandas as pd
import os
import sys
import argparse

# 添加项目根目录到系统路径
sys.path.append(
    os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)

# 导入letter模块的配置
from letter.config import current_config

# 配置命令行参数
parser = argparse.ArgumentParser(description="信访举报件处理程序")
parser.add_argument(
    "--excel_file", type=str, default="letter.xlsx", help="Excel文件路径"
)
args = parser.parse_args()

EXCEL_FILE = args.excel_file
REQUEST_TIMEOUT = 300  # 设置请求超时时间为300秒（5分钟）

# 根据环境配置构建API地址
API_URL = f"http://{current_config['host']}:{current_config['port']}/api/getLetters"

try:
    # 读取Excel文件
    df = pd.read_excel(EXCEL_FILE, sheet_name="Sheet1")

    print(f"正在处理Excel文件: {EXCEL_FILE}")
    print(f"共读取到 {len(df)} 条数据")

    # 遍历每一行数据
    for index, row in df.iterrows():
        # 准备请求数据
        test_data = {
            "bh": str(row["信访举报件编号"]),  # 确保编号为字符串类型
            "caseIntruction": str(row["原件描述"]),  # 确保描述为字符串类型
            "txm": (
                str(row["条形码"])
                if "条形码" in row and not pd.isna(row["条形码"])
                else ""
            ),
        }

        print(f"\n处理第 {index + 1} 条数据:")
        print("发送请求数据:")
        print(json.dumps(test_data, ensure_ascii=False, indent=2))

        try:
            response = requests.post(
                API_URL,
                json=test_data,
                timeout=REQUEST_TIMEOUT,  # 设置请求超时
            )

            # 检查响应状态码
            response.raise_for_status()

            # 尝试解析JSON响应
            try:
                result = response.json()
                print("\n响应状态码:", response.status_code)
                print("响应内容:")
                print(json.dumps(result, ensure_ascii=False, indent=2))

            except json.JSONDecodeError as e:
                print("JSON解析错误:", str(e))
                print("原始响应内容:", response.text)

        except requests.exceptions.Timeout:
            print(f"请求超时（{REQUEST_TIMEOUT}秒），跳过当前数据")
            continue
        except requests.exceptions.RequestException as e:
            print(f"请求错误: {str(e)}")
            continue

except FileNotFoundError:
    print(f"错误：找不到{EXCEL_FILE}文件")
except pd.errors.EmptyDataError:
    print("错误：Excel文件为空")
except Exception as e:
    print("其他错误:", str(e))
